const fs = require('fs')
const path = require("path")
// 配置数据库信息
const usersql = require('./mysql.js')
const setId = require('./assets/id.js')

exports.upLoadImgModule = (req, res, next) => {
    let files = req.files;
    let type = req.query.type
    let objid = req.query.objid
    let sqlarr = []
    let fileInfoArr = []
    for (let i in files) {
        let file = files[i]
        let fileInfo = {}
        let id = setId(10000000, 99999999)
        let fileName = "_" + file.filename + id + '.' +file.originalname.split('.')[1];
        let path = "public/images/" + fileName;
        fs.renameSync("./public/images/" + file.filename, path);
        //获取文件基本信息
        fileInfo.type = file.mimetype;
        fileInfo.name = fileName;
        fileInfo.size = file.size;
        fileInfo.path = path;
        let item = [objid, type, fileName] 
        sqlarr.push(item)
        fileInfoArr.push(fileInfo)
    }
    
    const sql = 'insert into photos(objid,type,photo) values ?'
    usersql.query(sql, [sqlarr], (err, results) => {
        if (err) return res.cc(err)
        if (results.affectedRows !== 0) {
            res.send({
                status: 200,
                msg: "OK",
                data: fileInfoArr,
            });
        }
    })
}

exports.downloadModule = (req, res) => {
    let photo = req.query.fileName
    let pathUrl = "./public/images/" + photo;
    const readStream = fs.createReadStream(pathUrl);
    const stats = fs.statSync(pathUrl);
    const filename = path.basename(pathUrl);
    res.writeHead(200, {
    'Content-Type': 'application/octet-stream', //告诉浏览器这是一个二进制文件
    'Content-Disposition': 'attachment; filename=' + filename, //告诉浏览器这是一个需要下载的文件
    'Content-Length': stats.size
    });
    readStream.pipe(res);
}

exports.getObjImg = (req, res) => {
    let objid = req.query.objid
    const sql = 'select * from photos where objid=?'
    usersql.query(sql, objid, (err, results) => {
        if (err) return res.cc(err)
        if (results.length !== 0) {
            res.send({ status: 200, message: '获取图片成功', data: results })
        } else {
            res.cc('请上传照片')
        }
    })
}

exports.deleteImg = (req, res) => {
    let photo = req.query.photo
    let objid = req.query.objid
    let pathUrl = "./public/images/" + photo
    const sql = 'delete from photos where photo=? and objid=?'
    usersql.query(sql, [photo, objid], (err, results) => {
        if (err) return res.cc(err)
        fs.unlink(pathUrl, (err) => {
            if(err) return res.cc(err);
            res.send({ status: 200, message: '删除图片成功' })
        })
    })
}



